package com.situ.mall.service.impl;

import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.Order;
import com.situ.mall.pojo.OrderItem;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.pojo.vo.OrderVO;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private SnowFlake snowFlake;

    @Override
    public void insert(Order order) {
        // 现在这个order对象里面已经有userId、shippingId、paymentType
        // 使用雪花算法生成订单主键
        long id = snowFlake.nextId();
        order.setOrderNo(id);
        // 订单状态:0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭
        order.setStatus(10);

        List<CartVO> cartVOList = cartMapper.selectByUserIdAndChecked(order.getUserId());
        BigDecimal payment = BigDecimal.valueOf(0.0);
        for (CartVO cartVO : cartVOList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setUserId(order.getUserId());
            orderItem.setOrderNo(id);
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductImage(cartVO.getMainImage());
            orderItem.setCurrentUnitPrice(cartVO.getPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            orderItem.setProductName(cartVO.getName());
            // 计算OrderItem中：商品价格*数量
            BigDecimal quantity = BigDecimal.valueOf(cartVO.getQuantity());
            BigDecimal cartItemTotalPrice = cartVO.getPrice().multiply(quantity);
            orderItem.setTotalPrice(cartItemTotalPrice);

            orderItemMapper.insert(orderItem);
            // 删除购物车中购物项，因为已经加入购物车
            cartMapper.deleteByPrimaryKey(cartVO.getId());

            // 每遍历一个OrderItem把总的价格加到payment上
            payment = payment.add(cartItemTotalPrice);
        }
        order.setPayment(payment);
        orderMapper.insert(order);

        // TODO： 插入完订单之后，去购物车里面删除这个用户刚才下单的商品
    }

    @Override
    public List<OrderVO> selectByUserId(Integer id) {
        return orderMapper.selectByUserId(id);
    }
}
